import pandas as pd
import hashlib
import numpy as np

def hash_dataframe(df, hash_algorithm='sha256', include_headers=True):
    """
    计算Pandas DataFrame数据的哈希值
    
    参数:
        df (DataFrame): Pandas DataFrame对象
        hash_algorithm (str): 哈希算法，如 'md5', 'sha1', 'sha256', 'sha512'
        include_headers (bool): 是否将列名包含在哈希计算中
        sort_data (bool): 是否在哈希计算前对数据进行排序
    
    返回:
        str: 数据的哈希值
    """
    if df is None or df.empty:
        raise ValueError("DataFrame为空或None")
    
    # 创建DataFrame的副本，避免修改原始数据
    df_copy = df.copy()
    
    # 处理NaN值，将其转换为空字符串
    df_copy = df_copy.fillna('')
    
    # 准备哈希计算的数据
    if include_headers:
        # 包含列名
        data_for_hash = []
        # 添加列名
        data_for_hash.append('|'.join(str(col) for col in df_copy.columns))
        # 添加数据行
        for _, row in df_copy.iterrows():
            data_for_hash.append('|'.join(str(cell) for cell in row))
        hash_input = '\n'.join(data_for_hash)
    else:
        # 仅数据内容
        hash_input = df_copy.to_csv(header=False, index=False, sep='|')
    
    # 计算哈希值
    hash_obj = hashlib.new(hash_algorithm)
    hash_obj.update(hash_input.encode('utf-8'))
    hash_value = hash_obj.hexdigest()
    
    return hash_value